<template>
  <div class="course-list-page">
    <div class="content-wrapper">
      <div class="page-header">
        <h1>课程列表</h1>
        <p>浏览和预约您感兴趣的健身课程</p>
      </div>

      <!-- 筛选和搜索区域 -->
      <div class="filter-section">
        <div class="filter-controls">
          <div class="search-box">
            <input
                type="text"
                v-model="searchQuery"
                placeholder="搜索课程名称或教练"
                class="search-input"
            />
          </div>
          <div class="filter-group">
            <label for="course-grade">课程等级：</label>
            <select id="course-grade" v-model="selectedGrade" class="filter-select">
              <option value="">全部</option>
              <option value="初级">初级</option>
              <option value="中级">中级</option>
              <option value="高级">高级</option>
            </select>
          </div>
          <div class="filter-group">
            <label for="course-status">课程状态：</label>
            <select id="course-status" v-model="selectedStatus" class="filter-select">
              <option value="">全部</option>
              <option value="未开始">未开始</option>
              <option value="即将开始">即将开始</option>
              <option value="进行中">进行中</option>
            </select>
          </div>
          <button @click="resetFilters" class="reset-btn">重置筛选</button>
        </div>
      </div>

      <!-- 课程展示区域 -->
      <div class="courses-container">
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p>加载课程中...</p>
        </div>

        <div v-else-if="filteredCourses.length === 0" class="empty-state">
          <img src="https://picsum.photos/seed/empty/500/300" alt="暂无课程" class="empty-image" />
          <p>没有找到符合条件的课程</p>
          <button @click="loadCourses" class="refresh-btn">刷新</button>
        </div>

        <div v-else class="courses-grid">
          <div
              v-for="course in filteredCourses"
              :key="course.cId"
              class="course-card"
              @click="goToCourseDetail(course.cId)"
          >
            <div class="course-image">
              <img
                  :src="course.cImage || 'https://picsum.photos/seed/course/500/300'"
                  :alt="course.cName"
                  class="course-pic"
              />
              <span class="status-badge" :class="getStatusClass(course)">
                {{ getCourseStatus(course) }}
              </span>
            </div>

            <div class="course-content">
              <h3 class="course-name">{{ course.cName }}</h3>

              <div class="course-meta">
                <div class="meta-item">
                  <i class="fa fa-clock-o"></i>
                  <span>{{ formatCourseTime(course.cTime) }}</span>
                </div>
                <div class="meta-item">
                  <i class="fa fa-signal"></i>
                  <span class="course-grade">{{ course.cGrade }}</span>
                </div>
                <div class="meta-item">
                  <i class="fa fa-users"></i>
                  <span class="course-capacity">
                    已预约: {{ course.cCurrent }}/{{ course.cMax }}
                  </span>
                </div>
              </div>

              <div class="course-actions">
                <button
                    class="view-detail-btn"
                    @click.stop="goToCourseDetail(course.cId)"
                >
                  查看详情
                </button>
                <button
                    v-if="canReserveCourse(course)"
                    class="reserve-btn"
                    @click.stop="reserveCourse(course.cId)"
                >
                  立即预约
                </button>
                <button
                    v-else
                    class="disabled-btn"
                    disabled
                >
                  {{ getReservationStatus(course) }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 预约弹窗 -->
    <CourseReservationModal
        v-model:visible="showReservationModal"
        :courseId="selectedCourseId"
        @reservation-success="onReservationSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { useUserStore } from '@/stores/auth';
import CourseReservationModal from '@/components/CourseReservationModal.vue';

const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const courses = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const selectedGrade = ref('');
const selectedStatus = ref('');
const showReservationModal = ref(false);
const selectedCourseId = ref(null);

// 计算课程当前状态
const getCourseStatus = (course) => {
  const now = new Date();
  const courseTime = new Date(course.cTime);
  const courseEndTime = new Date(courseTime.getTime() + course.cDuration * 60 * 1000); // 结束时间 = 开始时间 + 时长
  const oneDayBefore = new Date(courseTime.getTime() - 24 * 60 * 60 * 1000); // 前一天

  // 根据需求定义的时间范围计算状态
  // 只有课程开始前一天到课程开始时间才是即将开始
  if (now >= oneDayBefore && now < courseTime) {
    return '即将开始';
  } else if (now >= courseTime && now <= courseEndTime) {
    return '进行中';
  } else {
    // 距离课程开始时间还有超过一天的情况，返回"未开始"
    // 注意：已结束的课程不会显示在列表中
    return '未开始';
  }
};

// 计算属性：筛选后的课程列表
const filteredCourses = computed(() => {
  return courses.value.filter(course => {
    // 搜索筛选
    const matchesSearch = !searchQuery.value ||
        course.cName.toLowerCase().includes(searchQuery.value.toLowerCase());

    // 等级筛选
    const matchesGrade = !selectedGrade.value || course.cGrade === selectedGrade.value;

    // 状态筛选：使用前端重新计算的状态
    const currentStatus = getCourseStatus(course);
    const matchesStatus = !selectedStatus.value || currentStatus === selectedStatus.value;
    
    // 额外过滤：只显示未开始、即将开始和进行中的课程，隐藏已结束的课程
    const isEnded = new Date() > new Date(new Date(course.cTime).getTime() + course.cDuration * 60 * 1000);
    
    return !isEnded && matchesSearch && matchesGrade && matchesStatus;
  });
});

// 获取课程状态样式类
const getStatusClass = (course) => {
  const status = getCourseStatus(course);
  switch(status) {
    case '即将开始':
      return 'status-upcoming';
    case '进行中':
      return 'status-active';
    case '未开始':
      return 'status-future';
    default:
      return '';
  }
};

// 格式化课程时间
const formatCourseTime = (dateTime) => {
  if (!dateTime) return '';

  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return dateTime;

    const now = new Date();
    const isToday = date.toDateString() === now.toDateString();
    const isTomorrow = new Date(now.getTime() + 86400000).toDateString() === date.toDateString();

    // 格式化年月日
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const dateText = `${year}年${month}月${day}日`;
    
    // 格式化星期
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const weekdayText = weekdays[date.getDay()];
    
    // 格式化时间
    const timeText = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;

    return `${dateText} ${weekdayText} ${timeText}`;
  } catch (error) {
    console.error('时间格式化错误:', error);
    return dateTime;
  }
};

// 判断是否可以预约课程
const canReserveCourse = (course) => {
  if (!userStore.getIsLoggedIn || !userStore.userId) return false;
  if (course.cCurrent >= course.cMax) return false;

  const courseTime = new Date(course.cTime);
  const now = new Date();
  // 课程开始前2小时停止预约
  return courseTime > now && (courseTime - now) > 7200000; // 7200000毫秒 = 2小时
};

// 获取预约按钮状态文本
const getReservationStatus = (course) => {
  if (!userStore.getIsLoggedIn || !userStore.userId) return '请先登录';
  if (course.cCurrent >= course.cMax) return '名额已满';

  const courseTime = new Date(course.cTime);
  const now = new Date();
  if (courseTime > now && (courseTime - now) <= 7200000) {
    return '预约已截止';
  }

  return '立即预约';
};

// 跳转到课程详情
const goToCourseDetail = (courseId) => {
  router.push(`/course/detail/${courseId}`);
};

// 预约课程方法
const reserveCourse = (courseId) => {
  if (!userStore.getIsLoggedIn || !userStore.userId) {
    alert('请先登录后再预约课程');
    router.push('/auth/login');
    return;
  }

  selectedCourseId.value = courseId;
  showReservationModal.value = true;
};

const onReservationSuccess = () => {
  // 重新加载课程列表以更新人数
  loadCourses();
};

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = '';
  selectedGrade.value = '';
  selectedStatus.value = '';
};

// 加载课程列表
const loadCourses = async () => {
  loading.value = true;
  try {
    // 调用后端API获取可预约的课程
    const response = await axios.get('/api/courses/available');

    if (response.data && Array.isArray(response.data)) {
      courses.value = response.data
          .filter(course => course.cStatus === 1) // 只显示上架状态的课程
          .sort((a, b) => new Date(a.cTime) - new Date(b.cTime)); // 按开始时间升序排列
    } else {
      // 如果API返回格式不符合预期，使用模拟数据
      courses.value = getMockCourses();
    }
  } catch (error) {
    console.error('获取课程列表失败:', error);
    // API调用失败时使用模拟数据
    courses.value = getMockCourses();
  } finally {
    loading.value = false;
  }
};

// 模拟课程数据
const getMockCourses = () => {
  const now = new Date();
  const tomorrow = new Date(now.getTime() + 86400000);
  const dayAfterTomorrow = new Date(now.getTime() + 2 * 86400000);

  return [
    {
      cId: 1,
      cName: '瑜伽基础课',
      cGrade: '初级',
      cTime: tomorrow.toISOString(),
      cDuration: 60,
      cMax: 20,
      cCurrent: 8,
      cStatus: 1,
      c_run_status: '即将开始',
      cImage: 'https://picsum.photos/seed/yoga/500/300'
    },
    {
      cId: 2,
      cName: '高强度间歇训练',
      cGrade: '高级',
      cTime: dayAfterTomorrow.toISOString(),
      cDuration: 45,
      cMax: 15,
      cCurrent: 12,
      cStatus: 1,
      c_run_status: '即将开始',
      cImage: 'https://picsum.photos/seed/hiit/500/300'
    },
    {
      cId: 3,
      cName: '有氧拳击',
      cGrade: '中级',
      cTime: new Date(now.getTime() + 3 * 86400000).toISOString(),
      cDuration: 60,
      cMax: 25,
      cCurrent: 15,
      cStatus: 1,
      c_run_status: '即将开始',
      cImage: 'https://picsum.photos/seed/boxing/500/300'
    },
    {
      cId: 4,
      cName: '普拉提核心训练',
      cGrade: '中级',
      cTime: new Date(now.getTime() + 4 * 86400000).toISOString(),
      cDuration: 50,
      cMax: 18,
      cCurrent: 5,
      cStatus: 1,
      c_run_status: '即将开始',
      cImage: 'https://picsum.photos/seed/pilates/500/300'
    },
    {
      cId: 5,
      cName: '力量塑形',
      cGrade: '中级',
      cTime: new Date(now.getTime() + 5 * 86400000).toISOString(),
      cDuration: 60,
      cMax: 12,
      cCurrent: 8,
      cStatus: 1,
      c_run_status: '即将开始',
      cImage: 'https://picsum.photos/seed/strength/500/300'
    },
    {
      cId: 6,
      cName: '舞蹈健身课',
      cGrade: '初级',
      cTime: new Date(now.getTime() + 6 * 86400000).toISOString(),
      cDuration: 60,
      cMax: 30,
      cCurrent: 22,
      cStatus: 1,
      c_run_status: '即将开始',
      cImage: 'https://picsum.photos/seed/dance/500/300'
    }
  ];
};

// 组件挂载时加载课程
onMounted(() => {
  loadCourses();
});
</script>

<style scoped>
.course-list-page {
  padding: 20px;
  width: 100%;
  margin: 0;
  min-height: 100vh;
  background-color: #1a202c;
  background-image:
      radial-gradient(rgba(246, 173, 85, 0.05) 2px, transparent 2px),
      radial-gradient(rgba(45, 55, 72, 0.03) 2px, transparent 2px);
  background-size: 50px 50px;
  background-position: 0 0, 25px 25px;
  position: relative;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
}

.content-wrapper {
  width: 100%;
  max-width: 1400px;
  display: flex;
  flex-direction: column;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #f8fafc;
  margin-bottom: 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.page-header p {
  color: #cbd5e0;
  font-size: 1.1rem;
}

.filter-section {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.filter-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-box {
  flex: 1;
  min-width: 250px;
}

.search-input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 25px;
  font-size: 1rem;
  outline: none;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
}

.search-input:focus {
  border-color: #f6ad55;
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 0 0 2px rgba(246, 173, 85, 0.2);
}

.search-input::placeholder {
  color: #94a3b8;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-weight: 500;
  color: #cbd5e0;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  cursor: pointer;
  outline: none;
}

.filter-select option {
  background: #2d3748;
  color: #f8fafc;
}

.reset-btn {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  color: #cbd5e0;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
}

.reset-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-1px);
}

.courses-container {
  min-height: 400px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #cbd5e0;
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.1);
  border-top: 4px solid #f6ad55;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #cbd5e0;
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.empty-image {
  width: 150px;
  height: 150px;
  opacity: 0.5;
  margin-bottom: 20px;
  border-radius: 8px;
}

.refresh-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 15px;
  transition: all 0.3s;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #ed8936, #dd7714);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(246, 173, 85, 0.4);
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
}

.course-card {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.course-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 35px 60px rgba(0, 0, 0, 0.5);
  border-color: rgba(255, 255, 255, 0.15);
}

.course-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.course-pic {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.course-card:hover .course-pic {
  transform: scale(1.05);
}

.status-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 600;
  color: white;
}

.status-upcoming {
    background: linear-gradient(135deg, #48bb78, #38a169);
  }

  .status-active {
    background: linear-gradient(135deg, #4299e1, #3182ce);
  }

  .status-future {
    background: linear-gradient(135deg, #2196f3, #1976d2);
  }

.course-content {
  padding: 20px;
}

.course-name {
  font-size: 1.3rem;
  margin-bottom: 15px;
  color: #f8fafc;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.course-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.95rem;
  color: #cbd5e0;
}

.meta-item i {
  color: #f6ad55;
  width: 16px;
  text-align: center;
}

.course-grade {
  padding: 2px 8px;
  background: rgba(246, 173, 85, 0.2);
  color: #f6ad55;
  border-radius: 12px;
  font-size: 0.85rem;
  font-weight: 500;
}

.course-capacity {
  color: #f6ad55;
  font-weight: 500;
}

.course-actions {
  display: flex;
  gap: 10px;
}

.view-detail-btn,
.reserve-btn,
.disabled-btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 5px;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.view-detail-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.view-detail-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-1px);
}

.reserve-btn {
  background: linear-gradient(135deg, #f6ad55, #ed8936);
  color: white;
}

.reserve-btn:hover {
  background: linear-gradient(135deg, #ed8936, #dd7714);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(246, 173, 85, 0.4);
}

.disabled-btn {
  background: rgba(255, 255, 255, 0.05);
  color: #94a3b8;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box,
  .filter-group {
    width: 100%;
  }

  .courses-grid {
    grid-template-columns: 1fr;
  }
}
</style>